<?php

/**
 * Kupac form.
 *
 * @package    marketing
 * @subpackage form
 * @author     Your name here
 */
class KupacForm extends BaseKupacForm {

    public function configure() {
        $this->setWidgets(array(
            'id' => new sfWidgetFormInputHidden(),
            'korisnicko_ime' => new sfWidgetFormInput(),
            'lozinka' => new sfWidgetFormInputPassword(),
            'ponovite_lozinku' => new sfWidgetFormInputPassword(),
            'ime' => new sfWidgetFormInput(),
            'adresa' => new sfWidgetFormInput(),
            'racun' => new sfWidgetFormInput(),
            'telefon' => new sfWidgetFormInput(),
            'email' => new sfWidgetFormInput(),
           ));

        $this->setValidators(array(
            'id' => new sfValidatorPropelChoice(array('model' => 'Kupac', 'column' => 'id', 'required' => false)),
            'korisnicko_ime' => new sfValidatorString(array('max_length' => 15)),
            'lozinka' => new sfValidatorString(array('max_length' => 15)),
            'ponovite_lozinku' => new sfValidatorString(array('max_length' => 15)),
            'ime' => new sfValidatorString(array('max_length' => 15)),
            'adresa' => new sfValidatorString(array('max_length' => 45)),
            'racun' => new sfValidatorString(array('max_length' => 45)),
            'telefon' => new sfValidatorString(array('max_length' => 45)),
            'email' => new sfValidatorString(array('max_length' => 45)),
            ));

        $this->widgetSchema->setNameFormat('kupac[%s]');

        $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

        $this->validatorSchema->setPostValidator(
                new sfValidatorCallback(array('callback' => array($this, 'checkUsername')))
        );
    }

    public function checkUsername($validator, $values) {

        $c = new Criteria();
        $c->add(KupacPeer::KORISNICKO_IME, $values['korisnicko_ime'], Criteria::EQUAL);
        $kupac = KupacPeer::doSelectOne($c);
        if ($values['lozinka'] != $values['ponovite_lozinku']) {

            $error = new sfValidatorError($validator, 'Unete lozinke se razlikuju');
            throw new sfValidatorErrorSchema($validator, array('lozinka' => $error));
        }
        if ($kupac != null) {

            $error = new sfValidatorError($validator, 'Ne valja ime');
            throw new sfValidatorErrorSchema($validator, array('korisnicko_ime' => $error));
        }


        return $values;
    }

}
